package service;

import org.apache.commons.compress.compressors.z.ZCompressorInputStream;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by vonmax on 2019/10/17.
 */
public class CommonRun {

    public CommonRun() {
    }

    public static int DEFAULT_BUFFER_SIZE = 1024 * 1024;



    @Test
    public void run(){

        File tempFile = null;//创建临时文件
        FileOutputStream fos = null;

        try {
            //这里处理业务逻辑
            tempFile = File.createTempFile("temp", ".txt", new File("/Users/vonmax/Projects/Java_Study/src/main/resources/"));
            System.out.println("临时文件所在的本地路径：" + tempFile.getCanonicalPath());
            fos = new FileOutputStream(tempFile);
            byte [] data = "test line".getBytes();
            fos.write(data);

        } catch (Exception ex){
            System.out.println("exception :" + ex.toString());
        } finally {
            //关闭临时文件
            try{
                fos.flush();
                fos.close();
            } catch (Exception ex){

            }

            tempFile.delete();//程序退出时删除临时文件
        }
    }


    public static File unZFile(File file, String outFileName) {
        int buffersize = DEFAULT_BUFFER_SIZE;
        FileOutputStream out = null;
        ZCompressorInputStream zIn = null;
        try {
            FileInputStream fin = new FileInputStream(file);
            BufferedInputStream in = new BufferedInputStream(fin);
            File outFile = new File(outFileName);
            out = new FileOutputStream(outFile);
            zIn = new ZCompressorInputStream(in);
            final byte[] buffer = new byte[buffersize];
            int n = 0;
            while (-1 != (n = zIn.read(buffer))) {
                out.write(buffer, 0, n);
            }
            return outFile;
        } catch (Exception e) {
            System.out.println("解压Z文件失败");
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (zIn != null) {
                    zIn.close();
                }
            } catch (IOException e) {
                System.out.println("解压Z文件, 关闭流失败");
            }
        }
    }

    public static boolean compressZipFile(File rawFile, String outFileName, String outZipInnerName) {
        ZipOutputStream zos = null;
        InputStream is = null;
        try{
            zos = new ZipOutputStream(new FileOutputStream(outFileName));
            ZipEntry entry = new ZipEntry(outZipInnerName);//实例化压缩实体
            zos.setComment("处理后的银行账单压缩zip文件");  //设置注释
            zos.putNextEntry(entry);                    // 设置zip文件压缩实体, 也就是解压后的文件名
            is = new FileInputStream(rawFile);
            int len = 0;
            while ((len = is.read()) != -1) {
                zos.write(len);
            }

            return true;
        }catch (Exception e){
//            logHandler.logErrObj("压缩处理后的账单文件失败", e);
            System.out.println("压缩处理后的账单文件失败");
        }finally {
            try {
                if (null != is) {
                    is.close();
                }

                if (null != zos){
                    zos.close();
                }

            } catch (Exception e) {
//                logHandler.logErrObj("压缩处理后的账单文件，关闭流失败", e);
                System.out.println("压缩处理后的账单文件，关闭流失败");
            }
        }

        return false;
    }


    public static void splitByReg(String input){
        String[] splitedArray = input.split("(?=\\()|(?<=\\))|(?=\\[)|(?<=\\])|(?=\\{)|(?<=\\})");
        // 想要结果分四种：
        List <String> smallBracket = new ArrayList<String>();
        List <String> middleBracket = new ArrayList<String>();
        List <String> bigBracket = new ArrayList<String>();
        List <String> noBracket = new ArrayList<String>();

        // 遍历拆分数组
        for (String str: splitedArray){
            if (str.startsWith("(")){
                smallBracket.add(str.substring(1, str.length() - 1));
            }else if (str.startsWith("[")){
                middleBracket.add(str.substring(1, str.length() - 1));
            }else if (str.startsWith("{")){
                bigBracket.add(str.substring(1, str.length() - 1));
            }else{
                noBracket.add(str);
            }
        }

        // 在此处做业务处理
        System.out.println(smallBracket);
        System.out.println(middleBracket);
        System.out.println(bigBracket);
        System.out.println(noBracket);
    }



    public static String getFixedLengthWhiteSpace(int length) {
        return length <=  0? "" : String.format("%1$" + length + "s", " ");
    }


    public static String testMethod(Integer no){
        ++ no;
        return "test:" + no;
    }


    public static void processType01(String fileName){
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            //System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            int count = 0;
            // 一次读入一行，直到读入null为文件结束
            String code;
            String codeDesc;
            String codeStatus;

            StringBuilder failMap = new StringBuilder();
            StringBuilder processMap = new StringBuilder();
            while ((code = reader.readLine()) != null) {
                codeDesc = reader.readLine();
                codeStatus = reader.readLine();
                if (null != codeStatus && "失败状态".equals(codeStatus)){
                    //failStatusMap.put("0003", "消费交易失败");    //失败状态
                    failMap.append("failStatusMap.put(\"").append(code).append("\", \"").append(codeDesc).append("\");\n");
                    count ++;
                }

                else if (null != codeStatus && "中间状态".equals(codeStatus)){
                    //failStatusMap.put("0003", "消费交易失败");    //失败状态
                    processMap.append("processStatusMap.put(\"").append(code).append("\", \"").append(codeDesc).append("\");\n");
                    count ++;
                }





            }

            System.out.println(failMap.toString());
            System.out.println("//----------------------\n");
            System.out.println(processMap.toString());

            System.out.println("\n\n total line : " + count);

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }


    //判断字符串是不是以数字开头
    public static boolean isStartWithNumber(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str.charAt(0)+"");
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


    public static void processType02(String fileName){
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            //System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            int count = 0;
            // 一次读入一行，直到读入null为文件结束
            String code;
            String codeDesc;
            String codeStatus;

            StringBuilder failMap = new StringBuilder();
            StringBuilder processMap = new StringBuilder();

            List<String> codeStatusList = new ArrayList<String>();
            List<String> codeList = new ArrayList<String>();
            List<String> codeDescList = new ArrayList<String>();

            while ((codeStatus = reader.readLine()) != null){
                if (StringUtils.isBlank(codeStatus)){
                    continue;
                }

                if (isStartWithNumber(codeStatus)){
                    code = codeStatus;
                    codeList.add(code.split(" ")[0]);
                    codeDescList.add(code.split(" ")[1]);
                    break;
                }

                codeStatusList.add(codeStatus);
            }

            while ((code = reader.readLine()) != null) {
                if (StringUtils.isBlank(code)){
                    continue;
                }

                codeList.add(code.split(" ")[0]);
                codeDescList.add(code.split(" ")[1]);
            }



            System.out.println("codeList size: " + codeList.size());
            System.out.println("codeDescList size: " + codeDescList.size());
            System.out.println("codeStatusList size: " + codeStatusList.size());


            for (int i=0;i<codeDescList.size();++i){
                String innerCodeStatus = codeStatusList.get(i);
                String innerCode = codeList.get(i);
                String innerCodeDesc = codeDescList.get(i);

                if (null != innerCodeStatus && "失败状态".equals(innerCodeStatus)){
                    //failStatusMap.put("0003", "消费交易失败");    //失败状态
                    failMap.append("failStatusMap.put(\"").append(innerCode).append("\", \"").append(innerCodeDesc).append("\");\n");
                    count ++;
                }

                else if (null != innerCodeStatus && "中间状态".equals(innerCodeStatus)){
                    //failStatusMap.put("0003", "消费交易失败");    //失败状态
                    processMap.append("processStatusMap.put(\"").append(innerCode).append("\", \"").append(innerCodeDesc).append("\");\n");
                    count ++;
                }

                else{
                    System.out.println("error here: " + innerCode + " - " + innerCodeDesc + " - " + innerCodeStatus);
                }
            }


            System.out.println(failMap.toString());
            System.out.println("//----------------------\n");
            System.out.println(processMap.toString());

            System.out.println("\n\n total line : " + count);

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }


    public static void main(String[] args) {
        String input = "OrderStatus=0000&BankInstNo=700000000000013&BusiType=0001&TranType=0101&CompleteTime=204445&CompleteDate=20200218&CurryNo=CNY&AcqSeqId=0000000141732580&MerOrderNo=PAY14560734524201311&MerId=000092001198340&RemoteAddr=10.25.126.70&TranTime=204439&Version=20140728&Signature=dGGVE%2FLTA2tV8MDvyiUxYHEfGLoVxC05IZEwLl1nILA9K1bj91jqbek02znPRCEDNY0ZdtIeCne7A8tU26ra7bYRhctqev7ddg%2B3rUEm3fZGnuwI3Ln%2FgrAkBWuGStRAQ2MqLAM5sUneu6KMypeh2vXbV%2Bss1fczqPS%2BRVt%2BR0A%3D&TranDate=20200218&OrderAmt=1&AcqCode=000000000000014&AcqDate=20200218";

        String [] split = input.split("&");
        for (int i=0;i<split.length;++i){
            String [] line = split[i].split("=");
            System.out.println(line[0] + ":" + line[1]);
        }

    }





}
